package com.wxg.englishwordgather.process.file;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import com.alibaba.fastjson.JSON;
import com.wxg.englishwordgather.bean.TargetPage;
import com.wxg.englishwordgather.process.PageProcessor;
import com.wxg.englishwordgather.util.FileUtils;

public class JsonFileProcessor implements PageProcessor {

	private String dirpath = null;
	
	public JsonFileProcessor() {}
	
	public JsonFileProcessor(String dirpath) {
		this.dirpath = dirpath;
	}
	
	public List<TargetPage> process() {
		List<TargetPage> tplist = new ArrayList<TargetPage>();
		if (null == dirpath) return tplist;
		File[] files = FileUtils.listFilesf(dirpath);
		BufferedReader br = null;
		if ( null != files && files.length > 0 ) {
			try {
				for ( File f : files ){
					br = new BufferedReader(new InputStreamReader(new FileInputStream(f)));
					String line = null;
					StringBuilder sbb = new StringBuilder();
					while( (line=br.readLine()) != null){
						sbb.append( line ).append("\n");
					}
					TargetPage tp = JSON.parseObject(sbb.toString(), TargetPage.class);
					tplist.add(tp);
					sbb = null;
					br.close();
				}
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return tplist;
	}

	public String getDirpath() {
		return dirpath;
	}

	public void setDirpath(String dirpath) {
		this.dirpath = dirpath;
	}
	
}
